import { RouteRecordRaw } from "vue-router";
const moduleFile = require.context("@/views", true, /.vue$/);
// 异步路由处理（工程化获取映射组件）
export const addAsyncRoute = (asyncRoutes: Array<RouteRecordRaw>) => {
  // 获取 views文件夹下的文件目录
  const moduleFileKyes = moduleFile.keys();
  asyncRoutes.forEach((route: RouteRecordRaw) => {
    const compIndex = moduleFileKyes.findIndex(md => {
      if (md.includes("index.vue")) {
        const targetPath = formatFilePathtoRoutePath(md);
        return targetPath === route.path;
      }
      return false;
    });
    let component;
    if (compIndex > -1) {
      component = moduleFile(moduleFileKyes[compIndex]).default;
    } else {
      component = () => import("@/views/404.vue");
    }
    route.component = component;
  });
  return asyncRoutes;
};
export const formatFilePathtoRoutePath = (str: string) => {
  if (typeof str !== "string") {
    return "";
  }
  const reg = /^(.){1}|(\/index.vue){1}$/g;
  return str.replace(reg, "");
};
